package com.mybatis.jpa.statement.builder;

import com.mybatis.jpa.constant.ResultMapConstants;
import com.mybatis.jpa.meta.MybatisColumnMeta;
import com.mybatis.jpa.meta.PersistentMeta;
import com.mybatis.jpa.statement.MybatisStatementAdapter;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.SqlCommandType;
import java.lang.reflect.Method;

/**
 * 根据ids查询
 * @author wanglei
 * @date 2020 -02-06 11:06:32
 */
public class SelectByIdsBuilder extends  SelectPageBuilder{

    @Override
    public String buildSQL(PersistentMeta persistentMeta, Method method) {
        StringBuilder resultSql = new StringBuilder("<script> SELECT " + persistentMeta.getColumnNames() + " FROM ");
        resultSql.append(persistentMeta.getTableName());
        MybatisColumnMeta columnMeta = persistentMeta.getPrimaryColumnMeta();
        resultSql.append(" \n WHERE " + columnMeta.getColumnName() + " IN \n ");
        resultSql.append(" <foreach collection=\"ids\" index=\"index\" item=\"id\" open=\"(\" separator=\",\" close=\")\">" +
                "\n #{id}" +
                "\n</foreach>\n");
        return resultSql.toString();
    }

    @Override
    public void parseStatement(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method) {
        // 方法名
        adapter.setMethodName(method.getName());
        adapter.setParameterTypeClass(Object.class);
        String orderBy = getOrderByInfo(adapter, persistentMeta, method);
        // sqlScript
        adapter.setSqlScript(buildSQL(persistentMeta, method) + orderBy + "</script>");
        // 返回值类型
        adapter.setResultType(persistentMeta.getType());
        adapter.setResultMapId(ResultMapConstants.DEFAULT_NAMESPACE + "." + persistentMeta.getEntityName());
        adapter.setSqlCommandType(SqlCommandType.SELECT);
        // 主键策略
        adapter.setKeyGenerator(new NoKeyGenerator());
        adapter.setKeyProperty(null);
        adapter.setKeyColumn(null);
        adapter.parseStatement();
    }




}
